﻿using System.IO;

namespace DeskNote
{
    internal static class FileIO
    {
        private static string _message = string.Empty;

        internal static string Message
        {
            set
            {
                _message = value;
                WriteToFile(false);
            }
            get
            {
                ReadFromFile();
                return _message;
            }
        }

        internal static string UpdateMessage
        {
            set
            {
                _message = value;
                WriteToFile(true);
            }
        }

        private static void WriteToFile(bool append)
        {
            while (!IsFileReady()) { System.Threading.Thread.Sleep(100); }
            if (!string.IsNullOrEmpty(_message))
                using (StreamWriter writer = new StreamWriter(Settings.ToDoPath, append))
                {
                    writer.WriteLine(_message);
                }
        }

        private static void ReadFromFile()
        {
            while (!IsFileReady()) { System.Threading.Thread.Sleep(100); }
            using (StreamReader reader = new StreamReader(Settings.ToDoPath))
            {
                _message = reader.ReadToEnd();
            }
        }

        private static bool IsFileReady()
        {
            try
            {
                FileInfo fi = new FileInfo(Settings.ToDoPath);
                FileStream fs = fi.OpenWrite();
                fs.Close();
                fs.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
